package JDK动态代理;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/*
* 创建jdk的动态代理工具类
* */
public class DynamicProxy {

    /*被代理对象*/
    private Object target;

    public DynamicProxy(Object target) {
        this.target = target;
    }

    /*生成代理对象*/
    public Object getProxy(){
        ClassLoader classLoader = target.getClass().getClassLoader();
        Class<?>[] interfaces = target.getClass().getInterfaces();
        InvocationHandler invocationHandler = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                /*前置增强*/
                System.out.println(args[0]+"上课时间到了");
                Object invoke = method.invoke(target, args);
                /*后置增强*/
                System.out.println(args[0]+"下课时间到了");
                return invoke;
            }
        };
        Object o = Proxy.newProxyInstance(classLoader, interfaces, invocationHandler);
        return o;
    }
}
